package sys

import (
	"database/sql"
	"time"

	_ "github.com/go-sql-driver/mysql"
	"git.oschina.net/Ljohn/softCup/lib"
	"encoding/json"
	"errors"
	"fmt"
)
var db *sql.DB

func init(){
	var err error
	fmt.Println("正在开始初始化数据库.......")
	db,err = sql.Open("mysql", "?charset=utf8")
	if err!=nil || db==nil{
		fmt.Println("初始化连接失败_私有仓库  ----------> :",err)
	}
	db.SetMaxOpenConns(2000)
	db.SetMaxIdleConns(1000)
}

func SaveRepertoryUserInfo(username, encry_pwd, email string) error {
	if db==nil{
		return errors.New("数据库连接失败")
	}
	fmt.Println("私有仓库参数为： ",username,encry_pwd,email)
	//插入数据
	//stmt, err := db.Prepare("INSERT users SET username=?,email=?,encrypted_password=?,created_at=?")
	stmt,err := db.Prepare("call proc_reg_user(?,?,?,?)")
	if err != nil {
		return err
	}
	defer stmt.Close()
	_, err = stmt.Exec(username, email, encry_pwd, time.Now())
	if err != nil {
		return err
	}
	return nil
}

func GetRepertoryList(username string) ([]byte,error){
	if db==nil{
		return nil,errors.New("数据库连接失败")
	}
	stmt ,err :=db.Prepare(`SELECT
	  CONCAT(u.username,"/",r.name,":",t.name) as imgName,n.public,CONCAT((select hostname from registries where id =1),"/",u.username,"/",r.name,":",t.name) as host
FROM
	repositories AS r
INNER JOIN namespaces AS n ON n.id = r.namespace_id
INNER JOIN team_users AS tu ON tu.team_id = n.team_id
INNER JOIN users AS u ON u.id = tu.user_id
INNER JOIN tags as t ON t.repository_id = r.id
WHERE
	u.username = ?`)
	if err != nil {
		return nil,err
	}
	defer stmt.Close()
	rows, err := stmt.Query(username)
	if err != nil {
		return nil,err
	}
	defer rows.Close()
	res, _ := lib.GetKeyValuesAll(rows)
	temp, err := json.Marshal(res)
	if err != nil {
		return nil,err
	}
	return temp,nil
}







